package drugdealer.data;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * Singleton class ConnectionPool to manage SQL database connection pool.
 * 
 * @author dave
 */
public class ConnectionPool {

	private static ConnectionPool pool = null;
	private static DataSource dataSource = null;
	
	private ConnectionPool() {
		try {
			InitialContext ic = new InitialContext();
			dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/DrugDealerDB");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Method to retrieve the unique ConnectionPool object.
	 * @return instance of ConnectionPool from the database pool
	 */
	public static ConnectionPool getInstance() {
		if(pool == null)
			pool = new ConnectionPool();
		return pool;
	}
	
	/**
	 * Method to retrieve a Connection from the ConnectionPool object.
	 * @return a JDBC SQL Connection object.
	 * @return <code>null</code> in case of error.
	 */
	public Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Method to free used Connection.
	 * @param c Connection object to free.
	 */
	public void freeConnection(Connection c) {
		try {
			c.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
	}
}
